﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using System.Collections.Generic;
using PowerStation.RequestModel;
using Microsoft.EntityFrameworkCore;
using Masuit.Tools;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 警报管理
    /// </summary>
    public class AlarmController : BaseApi<AlarmController>
    {
        /// <summary>
        /// 警报管理
        /// </summary>
        /// <param name="content"></param>
        public AlarmController(IHttpContextAccessor content) : base(content)
        {
        }


        /// <summary>
        /// 新建警报信息`
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<decimal>> Create(tAlarm model)
        {
            await this.IsCheckPowerStation(model.alarmPowerStation_powerStationId_fk);
            model.alarmId = 0;
            model.addTime = null;
            model.pushTypeValue = 7;//默认全开启
            await this._db.tAlarm.AddAsync(model);
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<decimal>(true, model.alarmId);
        }


        /// <summary>
        /// 配置警报推送类型
        /// </summary>
        /// <param name="alarmId">警报ID</param>
        /// <param name="appPush">是否开启app推送</param>
        /// <param name="msmPush">是否开启短信推送</param>
        /// <param name="webPush">是否开启网页推送</param>
        [HttpPut]
        public async Task<ResultApi<int>> ConfigAlarmPushType(decimal alarmId,bool appPush,bool msmPush,bool webPush)
        {
            int v = 0;
            if (appPush) {
                v = v | 2;
            }
            if (webPush) {
                v = v | 1;
            }
            if (msmPush)
            {
                v = v | 4;

            }
            await this._db.tAlarm.Where(x => x.alarmId == alarmId).UpdateAsync(x => new tAlarm { pushTypeValue = v });
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<int>(true, v);
        }




        /// <summary>
        /// 修改警报信息
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> Modify(tAlarm model)
        {
            await this.IsCheckPowerStation(model.alarmPowerStation_powerStationId_fk);
            await this._db.tAlarm.Where(x => x.alarmId == model.alarmId).UpdateAsync(x => new tAlarm { 
                note = model.note,
                alamLevel = model.alamLevel,
                alarmDevice_deviceId_fk = model.alarmDevice_deviceId_fk,
                explain = model.explain
            });
            await this._db.SaveChangesAsync(); 
            return ResultApi.okOrError<bool>(true, true);
        }



        /// <summary>
        /// 删除警报信息
        /// </summary>
        /// <param name="alarmId">警报ID</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultApi<bool>> Delete(decimal alarmId)  
        {
            var model = await this._db.tAlarm.Where(x=>x.alarmId == alarmId && x.dataState != 1).Select(x=>x.alarmPowerStation_powerStationId_fk).ToListAsync();
            if (model.Any() == false) return ResultApi.error(false, "找不到数据");
            await this.IsCheckPowerStation(model.First());
            await this._db.tAlarm.Where(x => x.alarmId == alarmId).UpdateAsync(x=>new tAlarm { dataState = 1});
            await this._db.SaveChangesAsync();
            return ResultApi.okOrError<bool>(true, true);
        }


        /// <summary>
        /// 警报信息列表
        /// </summary>
        /// <param name="model">分页</param>
        /// <param name="alamLevel">警报级别,1:一级蓝色预警,2:二级黄色预警.3:三级橙色预警,4:四级红色预警</param>
        /// <param name="powerStationId">电站ID</param>
        /// <param name="name">警报名称,不搜索传空</param>
        /// <param name="topic">搜索主题</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vAlarm>>> List([FromQuery]PageModel model,decimal powerStationId,string name,string topic,int? alamLevel)
        {
            await this.IsCheckPowerStation(powerStationId);
            IQueryable<vAlarm> q = this._db.vAlarm;
            q = q.Where(x => x.dataState == 0 && x.alarmPowerStation_powerStationId_fk == powerStationId);
            if (alamLevel.HasValue)
            {
                q = q.Where(x=>x.alamLevel == alamLevel.Value);
            }
            if (!name.IsNullOrEmpty())
            {
                q = q.Where(x => x.deviceName.Contains(name));
            }
            if (!topic.IsNullOrEmpty()) {
                q = q.Where(x=>x.deviceTopic.Contains(topic));
            }
            q = q.OrderByDescending(x => x.alarmId);
            var result = await model.setPageAsync(q);
            return ResultApi.ok<List<vAlarm>>(await result.Item2.ToListAsync(), result.Item1); ;
        }


        /// <summary>
        /// 获取发生警报的数据
        /// </summary>
        /// <param name="level">警报级别,1:一级蓝色预警,2:二级黄色预警.3:三级橙色预警,4:四级红色预警</param>
        /// <param name="model">分页</param>
        /// <param name="name">预警名称</param>
        /// <param name="powerStationId">电站编号</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vAlarmMsg>>> MsgList(decimal powerStationId,string name,int? level,[FromQuery]PageModel model)
        {
            IQueryable<vAlarmMsg> q = this._db.vAlarmMsg.Where(x=>x.alarmPowerStation_powerStationId_fk == powerStationId);
            if (!string.IsNullOrEmpty(name))
            {
                q = q.Where(x => x.deviceName.Contains(name));
            }
            if (level.HasValue) {
                q = q.Where(x => x.alamLevel == level);
            }
            q = q.OrderByDescending(x => x.alarmMsgId);
            var result = await model.setPageAsync(q);
            return ResultApi.ok<List<vAlarmMsg>>(await result.Item2.ToListAsync(), result.Item1);
        }



        /// <summary>
        /// 绑定推送人员
        /// </summary>
        [HttpPut]
        public async Task<ResultApi<bool>> BindPushUser(RequestPushBindUserModel model)
        {
            var m = await this._db.tAlarm.FirstOrDefaultAsync(x => x.alarmId == model.alarmId);
            if (m == null) return ResultApi.error(false, "打不到警报数据");
            await this.IsCheckPowerStation(m.alarmPowerStation_powerStationId_fk);

            using (var tran = await this._db.Database.BeginTransactionAsync())
            {
                await this._db.tAlarmUser.Where(x => x.alarm_alarmId_fk == model.alarmId).DeleteAsync();
                await this._db.SaveChangesAsync();
                await this._db.tAlarmUser.AddRangeAsync(model.userId.Select(x=>new tAlarmUser { 
                    alarmUserId = 0,
                    alarmUser_userId_fk = x,
                    alarm_alarmId_fk = model.alarmId
                }));
                await this._db.SaveChangesAsync();
                await tran.CommitAsync();
            }
            return ResultApi.okOrError<bool>(true, true);
        }

        /// <summary>
        /// 返回绑定的推送人员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vAlarmUser>>> PushBindUserList(decimal alarmId)    
        {
            IQueryable<vAlarmUser> q = this._db.vAlarmUser.Where(x=>x.alarm_alarmId_fk == alarmId);
            return ResultApi.ok<List<vAlarmUser>>(await q.ToListAsync(), 0);
        }

        #region 报警类型一键导入

        /// <summary>
        /// 报警类型一键导入
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<bool>> AlarmListInsert(string stationID)
        {
            if (!stationID.All(char.IsDigit)) { return ResultApi.ok<bool>(false); }
            long id = long.Parse(stationID);
            IQueryable<tPowerStation> tPowerStations = this._db.tPowerStation.Where(x => x.powerStationId == id);
            if (tPowerStations == null) return ResultApi.ok<bool>(false);

            IQueryable<tPowerStationDevice> devlist = this._db.tPowerStationDevice.Where(x => x.devicePowerStation_powerStationId_fk == id && x.deviceType_keyId_fk == 820075);
            IQueryable<tAlarm> alarmlist2old = this._db.tAlarm.Where(x => x.alarmPowerStation_powerStationId_fk == id);
            List<tPowerStationDevice> devicelist = await devlist.ToListAsync();
            List<tAlarm> alalist = await alarmlist2old.ToListAsync();
            foreach (var item in alalist)
            {
                for (int i = 0; i < devicelist.Count; i++)
                {
                    if (item.alarmDevice_deviceId_fk == devicelist[i].deviceId)
                    {
                        devicelist.RemoveAt(i);
                    }
                }
            }
            List<tAlarm> list = new List<tAlarm>();
            foreach (var item in devicelist)
            {
                tAlarm t = new tAlarm()
                {
                    alarmDevice_deviceId_fk = item.deviceId,
                    alarmPowerStation_powerStationId_fk = item.devicePowerStation_powerStationId_fk,
                    alamLevel = 3,
                    explain = item.deviceName,
                    pushTypeValue = 7,
                    note = item.deviceDes ?? item.deviceName,
                    addTime = System.DateTime.Now,
                    dataState = 0
                };
                list.Add(t);
            }
            using (var db = await this._db.Database.BeginTransactionAsync())
            {
                await this._db.tAlarm.AddRangeAsync(list);
                await this._db.SaveChangesAsync();
                await db.CommitAsync();
            }
            return ResultApi.ok<bool>(true);
        }

        #endregion

        #region 批量设置报警推送名单
        /// <summary>
        /// 批量设置报警推送名单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultApi<bool>> AlarmList4User(string powerstationID,string userId)
        {
            if (!powerstationID.All(char.IsDigit)) { return ResultApi.ok<bool>(false); }
            long id = long.Parse(powerstationID);
            if (userId == null || userId.Equals("")) { return ResultApi.ok<bool>(false); }
            List<long> idlist = userId.Replace("[","").Replace("]", "").Split(",").Select(x => long.Parse(x)).ToList();
            List<vAlarm> devices = await this._db.vAlarm.Where(x => x.alarmPowerStation_powerStationId_fk == id).ToListAsync();
            foreach (var item in devices)
             {
                 List<long> userList2Alarm = await this._db.tAlarmUser
                     .Where(x => x.alarm_alarmId_fk == item.alarmId)
                     .Select(x => x.alarmUser_userId_fk)
                     .ToListAsync();
                 foreach (var user in idlist)
                 {
                     if (!userList2Alarm.Contains(user))
                     {
                         await this._db.tAlarmUser.AddRangeAsync(new tAlarmUser
                         {
                             alarmUser_userId_fk = user,
                             alarm_alarmId_fk = item.alarmId
                         });
                     }
                 }
             }
            await this._db.SaveChangesAsync();
            return ResultApi.ok<bool>(true);
        }
        #endregion
    }
}
